package com.sse.product.rbac.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.sse.product.rbac.entity.Role;
import com.sse.product.exception.BizRuntimeException;
import com.sse.product.rbac.mapper.RoleMapper;
import com.sse.product.rbac.service.IRoleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.Objects;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author junyongli
 * @since 2022-07-22
 */
@Service
public class RoleServiceImpl implements IRoleService {

    @Autowired
    private RoleMapper roleMapper;

    @Override
    @Transactional
    public Integer addRole(Role role) {
        List<Role> repeat = roleMapper.selectList(new LambdaQueryWrapper<Role>().eq(Role::getName, role.getName()));
        if (!CollectionUtils.isEmpty(repeat))
            throw new BizRuntimeException("角色的名称(name)不能为重复!");
        return roleMapper.insert(role);
    }

    @Override
    @Transactional
    public Integer updateRole(Role role) {
        Role roleEntity = roleMapper.selectById(role.getId());
        if (Objects.isNull(roleEntity))
            throw new BizRuntimeException("根据角色ID无法查到角色");
        if (StringUtils.hasText(role.getName())) {
            List<Role> roles = roleMapper.selectList(new LambdaQueryWrapper<Role>().eq(Role::getName, role.getName()));
            if (roles.stream().anyMatch(r -> !r.getId().equals(role.getId()))) {
                throw new BizRuntimeException("角色的名称(name)不能为重复!");
            }
        }
        return roleMapper.updateById(role);
    }

    @Override
    @Transactional
    public Integer delRol(Role role) {
        return roleMapper.deleteById(role);
    }

    @Override
    public List<Role> queryRoleByIds(List<Long> roleIds) {
        return roleMapper.selectBatchIds(roleIds);
    }

    @Override
    public List<Role> queryRole(String nameLike) {
        return roleMapper.selectList(new LambdaQueryWrapper<Role>().like(Role::getName, nameLike));
    }
}
